package com.hongxun.design.activitys;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hongxun.design.MyAPPActivity;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.bean.ConsumerInfo;
import com.hongxun.design.mytools.CheckClickTime;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.IntentToActivity;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.SetTypeface;
import com.hongxun.design.mytools.ShardPreferencesTool;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.mytools.VersionUtil;
import com.hongxun.design.ui.dialogstyle.MyDialog;
import com.hongxun.design.utils.ActionSheetUtil;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;
import com.hongxun.design.utils.imageutil.UriUtil;

/**
 * Created by zerdoor_pc on 2016/4/25.
 * 登录页
 */
public class LoginActivity extends BaseActivity {
    private SimpleDraweeView login_icon;
    TextView login_automaticsign_icon;
    public static String userName = "";
    public static String userPsw = "";
    EditText login_userpsw, login_username;
    private Handler loginHandler;
    String pswSecretkey = "(ANDROIDPEIWANGPSWLOGINACTIVITY)";//密钥头

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ShardPreferencesTool.saveshare(this, "APPFIRSTIN", false);
        TextView versionName = (TextView) findViewById(R.id.versionName);
        versionName.setText("版本号：" + VersionUtil.getVersionName(this));
        MyApp.openIdent = "";
        findView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        String psw = ShardPreferencesTool.getshare(this, MString.login_userpsw, "");
        psw = psw.replace(pswSecretkey, "");
        login_username.setText(ShardPreferencesTool.getshare(this, MString.login_username, ""));
        login_userpsw.setText(psw);

        if (userName.length() > 0 && userPsw.length() > 0) {
            login_username.setText(userName);
            login_userpsw.setText(userPsw);
        }

        //MyAPPActivity.getInstance().clear(this);
    }

    /**
     * 找到控件并初始化设置*
     */
    protected void findView() {
        login_username = (EditText) findViewById(R.id.login_username);//用户名
        login_userpsw = (EditText) findViewById(R.id.login_userpsw);//密码
        TextView login_user_icon = (TextView) findViewById(R.id.login_user_icon);//用户名图标
        TextView login_password_icon = (TextView) findViewById(R.id.login_password_icon);//密码图标
        TextView login_button_icon = (TextView) findViewById(R.id.login_button_icon);//登录图标
        login_automaticsign_icon = (TextView) findViewById(R.id.login_automaticsign_icon);//自动登录图标
        TextView login_forgetpassword_icon = (TextView) findViewById(R.id.login_forgetpassword_icon);//忘记密码图标
        TextView login_register_icon = (TextView) findViewById(R.id.login_register_icon);//注册图标
        login_icon = (SimpleDraweeView) findViewById(R.id.login_icon);//登陆头像
        login_icon.setImageURI(UriUtil.getUri(ShardPreferencesTool.getshare(this, MString.login_avatar, MString.LOCALIMAGEHEAD + R.mipmap.accountbitmap)));
        SetTypeface.set(login_user_icon, IconSourse.USER);
        SetTypeface.set(login_password_icon, IconSourse.PASSWORD);
        SetTypeface.set(login_button_icon, IconSourse.LOGINBUTTON);
        SetTypeface.set(login_automaticsign_icon, IconSourse.AUTOMATICSIGNUNCHECK);
        SetTypeface.set(login_forgetpassword_icon, IconSourse.FORGETPASSWORD);
        SetTypeface.set(login_register_icon, IconSourse.REGISTER);
        addLoginHandler();
        String psw = ShardPreferencesTool.getshare(this, MString.login_userpsw, "");
        psw = psw.replace(pswSecretkey, "");
        login_username.setText(ShardPreferencesTool.getshare(this, MString.login_username, ""));
        login_userpsw.setText(psw);
        if (ShardPreferencesTool.getshare(this, MString.logon_automatic, false)) {
            //自动登录
            SetTypeface.set(login_automaticsign_icon, IconSourse.AUTOMATICSIGNCHECK);
            Login();
        } else {
            SetTypeface.set(login_automaticsign_icon, IconSourse.AUTOMATICSIGNUNCHECK);
        }
    }

    //忘记密码
    public void forgetPassword(View v) {
        ActionSheetUtil.openSheetForRetrievePassword(this, DataUtil.getList(MString.SMS, MString.SECRET));
    }

    //自动登录
    public void automaticSign(View v) {
        if (login_automaticsign_icon.getText().equals(IconSourse.AUTOMATICSIGNCHECK)) {
            SetTypeface.set(login_automaticsign_icon, IconSourse.AUTOMATICSIGNUNCHECK);
            ShardPreferencesTool.saveshare(this, MString.logon_automatic, false);
        } else {
            SetTypeface.set(login_automaticsign_icon, IconSourse.AUTOMATICSIGNCHECK);
            ShardPreferencesTool.saveshare(this, MString.logon_automatic, true);
        }
    }

    //登录
    public void logon(View v) {
        Login();
    }

    //注册
    public void register(View v) {
        Bundle bundle = new Bundle();
        bundle.putString(MString.TYPE, MString.REGEDIT);
        IntentToActivity.intent(this, RegeditActivity.class, bundle);
    }


    private void Login() {
        if (CheckClickTime.back(this)) {
            if (login_username.getText().toString().length() == 0) {
                ToastShow.showShort(this, "用户名不能为空！");
                return;
            }

            if (login_userpsw.getText().toString().length() == 0) {
                ToastShow.showShort(this, "密码不能为空！");
                return;
            }

            if (!MyApp.NetWorkConnect) {
                ConsumerInfo bean = FastJsonUtil.JsonToLoginData(ShardPreferencesTool.getshare(this, MString.login_currusername, ""));
                if (bean != null && (bean.loginName.equals(login_username.getText().toString()) || bean.mobilePhone.equals(login_username.getText().toString())) && bean.pwd.equals(pswSecretkey + login_userpsw.getText().toString())) {

                    MyApp.userInfo.setBean(bean);
                    loginHandler.sendEmptyMessage(2);
                } else {
                    ToastShow.showShort(this, "用户名或密码有误，离线登陆失败！");
                }
            } else {
                //填写的文字
                ShardPreferencesTool.saveshare(this, MString.login_username, login_username.getText().toString());
                String psw = login_userpsw.getText().toString();
                ShardPreferencesTool.saveshare(this, MString.login_userpsw, pswSecretkey + psw);
                MyApp.HTTP.login(loginHandler, HttpStringUtil.SUCCESSED, login_username.getText().toString(), login_userpsw.getText().toString());
            }
        }
    }


    private void addLoginHandler() {
        loginHandler = new Handler() {
            String s = "";

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        s = "";
                        s = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                        if (s.equals(MString.TRUE) || s.equals(MString.FALSE)) {
                            MyApp.userInfo.setBean(FastJsonUtil.JsonToLoginData((String) msg.obj));
                            String psw = login_userpsw.getText().toString();
                            MyApp.userInfo.setPwd(ShardPreferencesTool.getshare(mActivity, MString.login_userpsw, pswSecretkey + psw));
                            MyApp.userInfo.setLoginName(ShardPreferencesTool.getshare(mActivity, MString.login_username, login_username.getText().toString()));
                            ShardPreferencesTool.saveshare(mActivity, MString.login_currusername, JSON.toJSONString(MyApp.userInfo));
                            JSONObject object = JSONObject.parseObject(String.valueOf(msg.obj));
                            //解决同时登陆问题
                            if (object.containsKey("openIdentuser")) {
                                String identuser = object.getString("openIdentuser");
                                ShardPreferencesTool.save(getApplicationContext(),"opou",identuser,1);
                            }
                            loginHandler.sendEmptyMessage(2);
                        } else {
                            ToastShow.showShort(mActivity, s);
                        }
                        MyDialog.Close();
                        break;
                    case 1:
                        s = "";
                        s = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                        if (s.equals(MString.TRUE) || s.equals(MString.FALSE)) {
                            MyApp.userInfo.setBean(FastJsonUtil.JsonToLoginData((String) msg.obj));
                            ToastShow.showShort(mActivity, "获取用户信息成功！");
                            IntentToActivity.intent(mActivity, HomePageActivity.class);
                            mActivity.finish();
                        } else {
                            ToastShow.showShort(mActivity, s);
                            IntentToActivity.intent(mActivity, HomePageActivity.class);
                            mActivity.finish();
                        }
                        break;
                    case 2:
                        String sys = ShardPreferencesTool.getshare(mActivity, MString.systemBaseInfo, "");
                        if (sys.length() == 0) {
                            ToastShow.showShort(mActivity, "系统信息无缓存,登陆失败！");
                            MyApp.handler.sendEmptyMessage(9);
                        } else {
                            ToastShow.showShort(mActivity, "登陆成功！");
                            MyApp.setAlias();//推送绑定别名
//                            MyApp.ChangeToOffLine();//新加操作
                            IntentToActivity.intent(mActivity, HomePageActivity.class);
                            mActivity.finish();
                        }
                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(mActivity, (String) msg.obj);
                        break;
                }
            }
        };
    }


    @Override
    public void onBackPressed() {
        back();
    }

    private long mExitTime;

    private void back() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            MyAPPActivity.getInstance().exit();
        }
    }

    private void ConsumerInfo() {
        MyApp.HTTP.ConsumerInfo(loginHandler, 1);
    }
}
